package com.hyxt.handler;

import com.alibaba.dubbo.config.annotation.Reference;
import com.hyxt.DTO.PlatConfig;
import com.hyxt.DTO.PlatLinks;
import com.hyxt.DTO.T809_MessageHeader;
import com.hyxt.DTO.protocol.JTBZF_0x04;
import com.hyxt.DTO.protocol.ProtocolUtil;
import com.hyxt.api.ChainLinkServer;
import com.hyxt.utils.BytesUtil;
import com.hyxt.utils.Caches;
import com.hyxt.utils.T809_Util;
import com.hyxt.utils.U809;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author songm
 * @version v1.0
 * @Description 从链路客户端数据处理类
 * @Date: Create in 22:03 2017/12/19
 * @Modifide By:
 **/
public class SlaveHandler extends SingleListenerHandler{

    private static final Log log = LogFactory.getLog(SlaveHandler.class);

    private PlatLinks platLinks = (PlatLinks) Caches.platLinks.get(getPlatId());
    //平台id
    private String platId;

    //平台配置文件
    private PlatConfig platConfig;

    //从链路通道名
    private String slaveChannel;

    //809链路管理
    @Reference(version = "1.0.0")
    private ChainLinkServer chainLinkServer;

    public SlaveHandler() {
    }

    public String getPlatId() {
        return platId;
    }

    public SlaveHandler(String slaveChannel) {
        this.slaveChannel = slaveChannel;
    }

    public void setPlatId(String platId) {
        this.platId = platId;
    }

    public PlatConfig getPlatConfig() {
        return platConfig;
    }

    public String getSlaveChannel() {
        return slaveChannel;
    }

    public void setSlaveChannel(String slaveChannel) {
        this.slaveChannel = slaveChannel;
    }

    public void setPlatConfig(PlatConfig platConfig) {
        this.platConfig = platConfig;
    }
    @Override
    public void process(String redisData) {
        //链路创建或销毁的消息
        String linkMag = redisData;
        String type = linkMag.split(":")[0];
        //如果是创建链路
        if ("channelActive".equalsIgnoreCase(type)){

        //如果是销毁链路
        }else if ("channelInactive".equalsIgnoreCase(type)){

        }else {
            byte[] message = redisData.getBytes();
            System.out.println("809从链路接入信息");
            // 这个位置,记录一下
            try {
                //反转义信息
                byte[] escape_msg  = T809_Util.reverseEscapeData(message);

                T809_MessageHeader header809 = T809_Util.getHeader(escape_msg);
                // 流水号 如果转发和809一致的话 可以直接用 不一样
                // 可能就要选择去绑定一下了<809流水号,转发流水号> 先直接写成用的一样的
                int responseSn = header809.getSn();
                int messageID = (int) header809.getMessageID();
                //System.out.println("809从联路接入信息");
                log.debug("<<<809从链路接入信息:" + BytesUtil.bytesToHexString(message)+"--"+BytesUtil.bytesToHexString(BytesUtil.int2bytes2(messageID)));

                switch (messageID) {

                    /** 前两种情况下 1.直接打包去回 2.我觉得在回之后额外加一个0x05直接去让他断开从链路 */

                    case 0x9002:// 从链路连接应答
                        //接收到从链路连接应答说明连接成功，将从链路平台id存入map
                        //subLink.put((String) config.get("platId"),"");
                        if (Caches.reqCache.containsKey(responseSn + "")) {
                            String accessCodeTmp_9002 = String.valueOf(Caches.reqCache.remove(responseSn + ""));
                            int businessId_9002 = Integer.valueOf(platId);
                            byte[] data = U809.changeSN(escape_msg, responseSn);
                            //System.out.println(BytesUtil.bytesToHexString(data));
                            data = U809.changeCode(escape_msg, Integer.valueOf(accessCodeTmp_9002));
                            data = U809.es(data);
                            slaveChannelUpCommand(businessId_9002, BytesUtil.int2bytes2(messageID), data);
                        }
                        break;
                    case 0x9006:// 从链路保持应答
                        if (Caches.reqCache.containsKey(responseSn + "")) {
                            //获取平台接入码
                            String accessCodeTmp_9006 = String.valueOf(Caches.reqCache.remove(responseSn + ""));
                            int businessId_9006 = Integer.valueOf(platId);
                            byte[] data = U809.changeSN(escape_msg, responseSn);
                            data = U809.changeCode(escape_msg, Integer.valueOf(accessCodeTmp_9006));
                            data = U809.es(data);
                            slaveChannelUpCommand(businessId_9006, BytesUtil.int2bytes2(messageID), data);
                        }
                        break;
                    case 0x9004:// 从链路注销应答
                        if (Caches.reqCache.containsKey(responseSn + "")) {
                            String accessCodeTmp_9004 = String.valueOf(Caches.reqCache.remove(responseSn + ""));
                            int businessId_9004 = Integer.valueOf(platId);
                            byte[] data = U809.changeSN(escape_msg, responseSn);
                            data = U809.changeCode(escape_msg, Integer.valueOf(accessCodeTmp_9004));
                            data = U809.es(data);
                            slaveChannelUpCommand(businessId_9004, BytesUtil.int2bytes2(messageID), data);
                        }
                        break;
                    case 0x9007:// 从连路断开通知 这个时候 要上一个0x05去通知从链路断开
                        break;
                    default:
                        break;
                }
            } catch (Exception protocolEscapeExeption) {
                protocolEscapeExeption.printStackTrace();
            }
        }
    }

    /**
     * 从链路上行809指令(0x04)
     * @param platId 平台id
     * @param business 指令编号
     * @param byte_809 809消息
     */
    void slaveChannelUpCommand(int platId, byte[] business, byte[] byte_809) {

        JTBZF_0x04 body_0x04 = new JTBZF_0x04();
        body_0x04.setUid(platId);
        body_0x04.setBusiness(business);
        body_0x04.setBytes_809(byte_809);

        final byte[] message = ProtocolUtil.getMessageByBody((byte) 0x04, body_0x04);

        //调用链路管理接口，通过转发链路发送上行消息
        chainLinkServer.sendMsg(slaveChannel,new String(message));
        /*transferChannel.writeAndFlush(message).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture arg0) throws Exception {
                if (arg0.isSuccess()) {
                    log.info(">>>交通部转发平台链路发送信息:" + BytesUtil.bytesToHexString(message));
                }

            }
        });*/

    }
}
